package io.github.harmonly.controller;

import io.github.harmonly.entity.User;
import io.github.harmonly.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminPageController {

    @Resource
    private UserService userService;

    @RequestMapping("/login")
    public ModelAndView login(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) new ModelAndView("redirect:/index");
        ModelAndView modelAndView = new ModelAndView("auth/admin_login");
        modelAndView.getModel().put("user", user);
        return modelAndView;
    }

    @RequestMapping("/register")
    public ModelAndView register() {
        ModelAndView modelAndView = new ModelAndView("auth/admin_register");
        modelAndView.getModel().put("user", null);
        return modelAndView;
    }

    @PostMapping("/doRegister")
    public String doRegister(String name, String account, String password, String role) {
        if (userService.addUser(User.builder()
                .name(name)
                .account(account)
                .password(password)
                .role(role)
                .face("/ss/static/images/default.png")
                .build())) return "redirect:login";
        return "redirect:register";
    }
}
